﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using NPOI.XWPF.UserModel;

namespace FillWordDataByTemplate.NpoiHelper
{
    /// <summary>
    /// 
    /// </summary>
    public class NpoiDocxExport
    {

        #region test

        private static void test()
        {
            //
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict["${电话}$"] = "13423433034";
            dict["${罚款}$"] = "99.88";
            dict["${交钱}$"] = "200.00";
            dict["${totalAmt}$"] = "300.00";

            //
            string filePath = @"D:\Studio\tzx-codes\用NPOI从Excel取数读Word模板生成多Word文件\FillWordDataByTemplate\_files_\这是模板2.docx";

            //
            NpoiDocxExport export = new NpoiDocxExport();
            export.ReplaceDict = dict;
            export.TemplateDocxFilePath = filePath;
            string message;
            bool ok = export.Export(out message);
            if (ok)
            {
                Process.Start(export.ExportNewFillPathName);
            }
            else
            {
                MessageBox.Show("失败:" + message);
            }
        }
        #endregion

        #region public

        /// <summary>
        /// 替代清单字典
        /// </summary>
        public IDictionary<string, string> ReplaceDict
        {
            get
            {
                if (_replaceDict == null)
                {
                    _replaceDict = new Dictionary<string, string>();
                }
                return _replaceDict;
            }
            set { _replaceDict = value; }
        }
        private IDictionary<string, string> _replaceDict = null;

        List<IDictionary<string, string>> ReplaceDictList
        {
            get { }
        } 

        /// <summary>
        /// 模板文件路径
        /// </summary>
        public string TemplateDocxFilePath
        {
            get { return _templateDocxFilePath; }
            set { _templateDocxFilePath = value; }
        }
        private string _templateDocxFilePath = null;

        /// <summary>
        /// 导出子文件夹名(默认日期时间字符串)
        /// </summary>
        public string NewSubDirName
        {
            get
            {
                if (_exportSubDir == null)
                {
                    _exportSubDir = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                }
                return _exportSubDir;
            }
            set
            {
                string v = string.Format("{0}", value).Replace("\\","_").Replace("/","_");
                _exportSubDir = v;
            }
        }
        private string _exportSubDir = null;

        /// <summary>
        /// 导出文件名(默认GUID字符串)
        /// </summary>
        public string NewDocxName
        {
            get
            {
                if (_exportDocxFileName == null)
                {
                    _exportDocxFileName = Guid.NewGuid().ToString().ToLower().Replace("-", "") + ".docx";
                }
                return _exportDocxFileName;
            }
            set
            {
                string v = string.Format("{0}", value).Replace("\\", "_").Replace("/", "_").Replace(".","_");
                _exportDocxFileName = v;
            }
        }
        private string _exportDocxFileName = null;

        /// <summary>
        /// 成功导出新文件后,返回新文件完整路径名称
        /// </summary>
        public string ExportNewFillPathName
        {
            get { return _exportNewFillPathName; }
        }
        private string _exportNewFillPathName = null;

        //return @"E:\Users\Documents\Visual Studio 2013\Projects\用NPOI读写Word\FillWordDataByTemplate\_files_\这是模板2.docx";

        /// <summary>
        /// 导出
        /// </summary>
        public bool Export(out string message)
        {
            message = null;
            if (string.IsNullOrEmpty(TemplateDocxFilePath))
            {
                message = "模板文件路径为空";
                return false;
            }
            if (!File.Exists(TemplateDocxFilePath))
            {
                message = "模板文件不存在";
                return false;
            }

            //保存位置
            string exePath = Path.GetDirectoryName(TemplateDocxFilePath);
            if (string.IsNullOrEmpty(exePath))
            {
                exePath = "C:\\";
            }
            string fileNew = string.Format("{0}\\{1}\\{2}",
                exePath.TrimEnd('\\'),
                NewSubDirName,
                NewDocxName
                );
            string savePath = string.Format("{0}",Path.GetDirectoryName(fileNew));
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            //模板
            using (Stream fs_template = new FileStream(TemplateDocxFilePath, FileMode.Open, FileAccess.Read))
            {
                XWPFDocument doc = new XWPFDocument(fs_template);

                //替换段落里面的变量  
                Replace_Paragraph(doc, ReplaceDict);

                //替换表格里面的变量  
                Replace_Table(doc, ReplaceDict);

                using (Stream fs_newfile = new FileStream(fileNew, FileMode.Create, FileAccess.Write))
                {
                    doc.Write(fs_newfile);
                    fs_template.Close();//关
                }//using

                fs_template.Close();//关
            }//using

            //返回
            _exportNewFillPathName = fileNew;
            return true;
        }

        #endregion

        #region Replace

        /// <summary>
        /// 替换段落里面的变量</summary>
        /// <param name="doc">要替换的文档</param>
        /// <param name="params3">参数</param>
        private void Replace_Paragraph(XWPFDocument doc, IDictionary<string, string> params3)
        {
            IEnumerator<XWPFParagraph> iterator = doc.GetParagraphsEnumerator();
            XWPFParagraph para;
            while (iterator.MoveNext())
            {
                para = iterator.Current;
                Replace_Paragraph(para, params3);
            }
        }

        /// <summary>
        /// 替换表格里面的变量</summary>
        /// <param name="doc">要替换的文档</param>
        /// <param name="params4">参数</param>
        private void Replace_Table(XWPFDocument doc, IDictionary<string, string> params4)
        {
            IEnumerator<XWPFTable> iterator = doc.GetTablesEnumerator();
            XWPFTable table;
            IList<XWPFTableRow> rows;
            IList<XWPFTableCell> cells;
            IList<XWPFParagraph> paras;
            while (iterator.MoveNext())
            {
                table = iterator.Current;
                rows = table.Rows;
                foreach (XWPFTableRow row in rows)
                {
                    cells = row.GetTableCells();
                    foreach (XWPFTableCell cell in cells)
                    {
                        paras = cell.Paragraphs;
                        foreach (XWPFParagraph para in paras)
                        {
                            Replace_Paragraph(para, params4);
                        }//foreach paragraph
                    }//foreach cell
                }//foreach row
            }//while
        }

        /// <summary>
        /// 替换段落里面的变量</summary>
        /// <param name="para">要替换的段落</param>
        /// <param name="params5">参数</param>
        private void Replace_Paragraph(XWPFParagraph para, IDictionary<string, string> params5)
        {
            foreach (KeyValuePair<string, string> kv in params5)
            {
                if (para.Text.Contains(kv.Key))
                {
                    para.ReplaceText(kv.Key, kv.Value);
                }
            }
        }

        #endregion

    }
}
